//
//  ViewController.swift
//  表情键盘
//
//  Created by iOS on 16/9/26.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 在弹出键盘之前设置自定义的键盘
//        textView.inputView = UIButton(type: .contactAdd)
        let keyboarView = HMEmoticonKeyboardView.emoticonKeyboardView()
        keyboarView.textView = textView
        textView.inputView = keyboarView
        
        textView.becomeFirstResponder()
        
        // 测试加载数据
//        let packages = HMEmoticonManager.shared.loadEmoticonPackages()
//        let packages = HMEmoticonManager.shared.packages
//        print("packages: \(packages)")
        
//        testEmoji()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let text = textView.emoticonNameText()
        print("text = \(text)")
    }
    
    private func test() {
        // 获取textView属性文本中的内容
        // textView中的属性文本内容是分段保存的,普通文本一段,图片一段,emoji一段
        //        print("textView.attributedText = \(textView.attributedText)")
        // 遍历属性文本中的每一段内容
        
        var text: String = ""
        let range = NSRange(location: 0, length: textView.attributedText.length)
        textView.attributedText.enumerateAttributes(in: range, options: []) { (dict, range, _) in
            // 每次遍历到一段内容就会调用一次, 可以根据范围截取需要字符串,如果是图片,在dict中会包含 NSAttachment 这个key
            //            print("遍历到了内容: range:\(range.location) - \(range.length), dict: \(dict)")
            
            if let attachment = dict["NSAttachment"] as? HMTextAttachment {
                // 图片表情
                text += attachment.chs ?? "找不到表情"
            } else {
                // 普通文本或emoji表情,截取文本
                let str = (textView.attributedText.string as NSString).substring(with: range)
                
                text += str
            }
        }
        
        print("最终拼接好的字符串: \(text)")
    }
    
    private func testEmoji() {
        // 0x1f341
        let code = "0x1f341"
        
        // 扫描器
        let scanner = Scanner(string: code)
        
        // result: UnsafeMutablePointer<UInt32>?: 不安全的可变的 UInt32 类型的指针
        var result: UInt32 = 0
        scanner.scanHexInt32(&result)
        
        print("result: \(result)")
        
        let emoji = String(Character(UnicodeScalar(result)!))
        
        textView.text = emoji
    }
}

